package com.hxgis.statisticanalysis.intelligentIndicator.service;


import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import com.hxgis.export.DocxResolver;
import com.hxgis.export.ExpressionResolver;
import com.hxgis.statisticanalysis.intelligentIndicator.dao.jpa.*;
import com.hxgis.statisticanalysis.intelligentIndicator.vo.NetworkResolveVo;
import com.hxgis.statisticanalysis.intelligentIndicator.pojo.*;
import com.hxgis.statisticanalysis.intelligentIndicator.vo.CityNetWorkVO;
import com.hxgis.statisticanalysis.intelligentIndicator.vo.NetWorkVO;
import com.hxgis.statisticanalysis.utils.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IntelligentIndicatorService {
    @Autowired
    private ModernIndexJpa modernIndexJpa;
    @Autowired
    private FailureRecordJpa failureRecordJpa;
    @Autowired
    private ModernIndexScoreJpa modernIndexScoreJpa;
    @Autowired
    private FailureMappingJpa failureMappingJpa;
    @Autowired
    private IndexConfigJpa indexConfigJpa;
    @Autowired
    private DataPathCom dataPathCom;

    private final String EXCEL_TEMPLATE = "modernIndexTemplate.xlsx";
    private final String EXCEL_TEMPLATE1 = "netWorkTemplate.docx";
    private XSSFCellStyle cellStyle;
    private XSSFCellStyle titleStyle;


    public String exportExcel(HttpServletResponse response, String[] dateTime) throws IOException {
        //查询每年的数值和分数
        Map<String, List<ModernIndex>> modernIndexMap = modernIndexJpa.findByDateTimeIn(dateTime).stream().collect(Collectors.groupingBy(ModernIndex::getDateTime));
        Map<String, List<ModernIndexScore>> modernIndexScoreMap = modernIndexScoreJpa.findByDateTimeIn(dateTime).stream().collect(Collectors.groupingBy(ModernIndexScore::getDateTime));
        String path = dataPathCom.getRootPath() + EXCEL_TEMPLATE;
        File file = new File(path);
        if (!file.exists()) {
            return "模板文件" + path + "不存在！";
        }
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
        XSSFSheet sheet = workbook.getSheet("现代化指标监控");
        //获取样式
        cellStyle = ExcelUtil.getCellStyle(workbook, null, false);
        titleStyle = ExcelUtil.getCellStyle(workbook, null, true);
        int index = 2;
        //给map集合排序
        Map<String, List<ModernIndex>> sorted = new TreeMap(modernIndexMap);
        for (String s : sorted.keySet()) {
            ModernIndex modernIndex = modernIndexMap.get(s).get(0);
            ModernIndexScore modernIndexScore = new ModernIndexScore();
            if (CollectionUtils.isNotBlank(modernIndexScoreMap.get(s))) {
                modernIndexScore = modernIndexScoreMap.get(s).get(0);
            }
            XSSFRow row = sheet.getRow(0);
            XSSFCell cell = row.createCell(index);
            cell.setCellValue(s + "年");
            cell.setCellStyle(titleStyle);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, index, index + 1));
            ExcelUtil.setBorderStyle(new CellRangeAddress(0, 0, index, index + 1), sheet);
            row = sheet.getRow(1);
            setCellValue(row, "数值", index);
            setCellValue(row, "得分", index + 1);
            row = sheet.getRow(2);
            setCellValue(row, String.valueOf(modernIndex.getCpuNum()), index);
            setCellValue(row, String.valueOf(modernIndexScore.getCpuNum()), index + 1);
            row = sheet.getRow(3);
            setCellValue(row, modernIndex.getCpuStorage(), index);
            setCellValue(row, modernIndexScore.getCpuStorage(), index + 1);
            row = sheet.getRow(4);
            setCellValue(row, modernIndex.getCpuDayAvg(), index);
            setCellValue(row, modernIndexScore.getCpuDayAvg(), index + 1);
            row = sheet.getRow(5);
            setCellValue(row, modernIndex.getCpuDayMax(), index);
            setCellValue(row, modernIndexScore.getCpuDayMax(), index + 1);
            row = sheet.getRow(6);
            setCellValue(row, modernIndex.getCpuStorageRate(), index);
            setCellValue(row, modernIndexScore.getCpuStorageRate(), index + 1);
            row = sheet.getRow(7);
            setCellValue(row, modernIndex.getProvinceLink(), index);
            setCellValue(row, modernIndexScore.getProvinceLink(), index + 1);
            row = sheet.getRow(8);
            setCellValue(row, modernIndex.getCountyLink(), index);
            setCellValue(row, modernIndexScore.getCountyLink(), index + 1);
            row = sheet.getRow(9);
            setCellValue(row, modernIndex.getCountyRate(), index);
            setCellValue(row, modernIndexScore.getCountyRate(), index + 1);
            row = sheet.getRow(10);
            setCellValue(row, modernIndex.getNetworkExit(), index);
            setCellValue(row, modernIndexScore.getNetworkExit(), index + 1);
            row = sheet.getRow(11);
            setCellValue(row, modernIndex.getThreeLevelSystemRate(), index);
            setCellValue(row, modernIndexScore.getThreeLevelSystemRate(), index + 1);
            row = sheet.getRow(12);
            setCellValue(row, modernIndex.getThreeLevelSystemAvg(), index);
            setCellValue(row, modernIndexScore.getThreeLevelSystemAvg(), index + 1);
            row = sheet.getRow(13);
            setCellValue(row, modernIndex.getNetworkSecurityIncidents(), index);
            setCellValue(row, modernIndexScore.getNetworkSecurityIncidents(), index + 1);
            row = sheet.getRow(14);
            setCellValue(row, String.valueOf(modernIndex.getDataCollectNum()), index);
            setCellValue(row, modernIndexScore.getDataCollectNum(), index + 1);
            row = sheet.getRow(15);
            setCellValue(row, modernIndex.getRegionDataCollectTime(), index);
            setCellValue(row, modernIndexScore.getRegionDataCollectTime(), index + 1);
            row = sheet.getRow(16);
            setCellValue(row, modernIndex.getRadarDataCollectTime(), index);
            setCellValue(row, modernIndexScore.getRadarDataCollectTime(), index + 1);
            row = sheet.getRow(17);
            setCellValue(row, modernIndex.getDataCollectRate(), index);
            setCellValue(row, modernIndexScore.getDataCollectRate(), index + 1);
            row = sheet.getRow(18);
            setCellValue(row, modernIndex.getCollectRate(), index);
            setCellValue(row, modernIndexScore.getCollectRate(), index + 1);
            row = sheet.getRow(19);
            setCellValue(row, modernIndex.getControlDataNum(), index);
            setCellValue(row, modernIndexScore.getControlDataNum(), index + 1);
            row = sheet.getRow(20);
            setCellValue(row, modernIndex.getQualityDataScore(), index);
            setCellValue(row, modernIndexScore.getQualityDataScore(), index + 1);
            row = sheet.getRow(21);
            setCellValue(row, modernIndex.getProvinceNewAlgorithm(), index);
            setCellValue(row, modernIndexScore.getProvinceNewAlgorithm(), index + 1);
/*            row = sheet.getRow(22);
            setCellValue(row, modernIndex.getCountyNewAlgorithm(), index);
            setCellValue(row, modernIndexScore.getCountyNewAlgorithm(), index + 1);*/
            row = sheet.getRow(22);
            setCellValue(row, modernIndex.getUpdateAlgorithm(), index);
            setCellValue(row, modernIndexScore.getUpdateAlgorithm(), index + 1);
            row = sheet.getRow(23);
            setCellValue(row, modernIndex.getShareAlgorithm(), index);
            setCellValue(row, modernIndexScore.getShareAlgorithm(), index + 1);
            row = sheet.getRow(24);
            setCellValue(row, modernIndex.getProductOutputTypes(), index);
            setCellValue(row, modernIndexScore.getProductOutputTypes(), index + 1);
            row = sheet.getRow(25);
            setCellValue(row, modernIndex.getInterfaceResponseTime(), index);
            setCellValue(row, modernIndexScore.getInterfaceResponseTime(), index + 1);
            row = sheet.getRow(26);
            setCellValue(row, modernIndex.getDataAccess(), index);
            setCellValue(row, modernIndexScore.getDataAccess(), index + 1);
            row = sheet.getRow(27);
            setCellValue(row, modernIndex.getDataService(), index);
            setCellValue(row, modernIndexScore.getDataService(), index + 1);
            row = sheet.getRow(28);
            setCellValue(row, modernIndex.getIndustryCoverage(), index);
            setCellValue(row, modernIndexScore.getIndustryCoverage(), index + 1);
            row = sheet.getRow(29);
            setCellValue(row, modernIndex.getNetworkManagment(), index);
            setCellValue(row, modernIndexScore.getNetworkManagment(), index + 1);
            row = sheet.getRow(30);
            setCellValue(row, String.valueOf(modernIndex.getCoreDataNum()), index);
            setCellValue(row, modernIndexScore.getCoreDataNum(), index + 1);
            row = sheet.getRow(31);
            setCellValue(row, String.valueOf(modernIndex.getTianqingSystemNum()), index);
            setCellValue(row, modernIndexScore.getTianqingSystemNum(), index + 1);
            row = sheet.getRow(32);
            setCellValue(row, String.valueOf(modernIndex.getTianjingSystemNum()), index);
            setCellValue(row, modernIndexScore.getTianjingSystemNum(), index + 1);
            index += 2;
        }
        ExportUtil.exportExcel(response, workbook, "报表导出");
        return null;
    }

    private void setCellValue(XSSFRow row, String value, int index) {
        XSSFCell cell = row.createCell(index);
        cell.setCellValue(value);
        cell.setCellStyle(cellStyle);
    }

    private void setCellValue(XSSFRow row, Double value, int index) {
        XSSFCell cell = row.createCell(index);
        String s = String.valueOf(value);
        if (!s.equals("null")) {
            cell.setCellValue(s);
        }
        cell.setCellStyle(cellStyle);
    }


    public String exporNetWorktExcel(HttpServletResponse response, String date) throws IOException, XmlException, InvalidFormatException {
        List<FailureRecord> byDeclareTimeBetweenAnd = failureRecordJpa.findByDateTime(date);
        Collections.sort(byDeclareTimeBetweenAnd, (o1, o2) -> (int) (DateUtil.str2DateByFormat(o1.getDeclareTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime() - DateUtil.str2DateByFormat(o2.getDeclareTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime()));

        //准备数据
        FailureWordBean failureWordBean = new FailureWordBean();
        String[] split = date.split("-");
        String year = split[0];
        String month = split[1];
        failureWordBean.setYear(year);
        failureWordBean.setMonth(month);
        List<FailureWordBean.SubBean> dataList = new ArrayList<>();
        for (FailureRecord failureRecord : byDeclareTimeBetweenAnd) {
            FailureWordBean.SubBean subBean = new FailureWordBean.SubBean();
            BeanUtils.copyProperties(failureRecord, subBean);
            dataList.add(subBean);
        }
        failureWordBean.setTableList(dataList);

        //解析
        String path = dataPathCom.getRootPath() + EXCEL_TEMPLATE1;
        File file = new File(path);
        if (!file.exists()) {
            return "模板文件" + path + "不存在！";
        }

        DocxResolver docxResolver = new DocxResolver(new ExpressionResolver(failureWordBean));
        XWPFDocument document = new XWPFDocument(new FileInputStream(file));
        docxResolver.resolve(document);

        //按列填充第二个表格
        List<CityNetWorkVO> netWorkInfo = getNetWorkInfo(date);
        XWPFTable table = document.getTables().get(1);

        int index = 0;

        //获取表格的
        for (CityNetWorkVO cityNetWorkVO : netWorkInfo) {
            for (int i = 1; i <= 7; i++) {
                XWPFTableRow row = table.getRow(0);
                if (row.getCell(i).getText().equals(cityNetWorkVO.getCity())) {
                    XWPFTableRow row1 = table.getRow(1);
                    XWPFTableRow row2 = table.getRow(2);
                    writeData(row1.getCell(i), cityNetWorkVO.getSum());
                    writeData(row2.getCell(i), cityNetWorkVO.getHours());
                    break;
                }
                XWPFTableRow row3 = table.getRow(3);
                if (row3.getCell(i).getText().equals(cityNetWorkVO.getCity())) {
                    XWPFTableRow row4 = table.getRow(4);
                    XWPFTableRow row5 = table.getRow(5);
                    writeData(row4.getCell(i), cityNetWorkVO.getSum());
                    writeData(row5.getCell(i), cityNetWorkVO.getHours());
                    break;
                }
            }
        }
        String fileName = year + "年" + month + "月广西气象宽带网及网络设备故障情况报告";
        ExportUtil.exportDoc(response, document, fileName);
        return null;
    }

    private void writeData(XWPFTableCell cell, String value) {
        XWPFParagraph cellParagraph = cell.getParagraphs().get(0);
        //删除表格中原有的文本
        cellParagraph.removeRun(0);
        ExportUtil.setCellValue(cell, value);
    }

    public List<CityNetWorkVO> getNetWorkInfo(String date) {
        List<FailureRecord> byDateTime = failureRecordJpa.findByDateTime(date);
        Map<String, List<FailureRecord>> collect = byDateTime.stream().collect(Collectors.groupingBy(failureRecord -> failureRecord.getSerialNumber().substring(0, 5)));
        List<NetWorkVO> dataList = new ArrayList<>();
        List<FailureMapping> allMapping = failureMappingJpa.getAllMapping();
        Map<String, List<FailureMapping>> allStationMap = allMapping.stream().collect(Collectors.groupingBy(FailureMapping::getStationNo));
        //统计每个站点的故障次数和时长
        collect.forEach((s, failureRecords) -> {
            double hour = 0;
            for (FailureRecord failureRecord : failureRecords) {
                long time = DateUtil.str2DateByFormat(failureRecord.getStartTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime();
                long getSolveTime = DateUtil.str2DateByFormat(failureRecord.getSolveTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime();
                hour += (getSolveTime - time) / CommonValue.hour;
            }
            FailureMapping failureMapping = allStationMap.get(s).get(0);
            BigDecimal bd = new BigDecimal(hour);
            hour = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            NetWorkVO netWorkVO = new NetWorkVO();
            netWorkVO.setStationId(s);
            netWorkVO.setHours(String.valueOf(hour));
            netWorkVO.setCity(failureMapping.getUnits());
            netWorkVO.setStationName(failureMapping.getStationName());
            netWorkVO.setSum(String.valueOf(failureRecords.size()));
            dataList.add(netWorkVO);
        });
        //按市区分组
        List<CityNetWorkVO> voList = new ArrayList<>();
        Map<String, List<NetWorkVO>> cityMap = dataList.stream().collect(Collectors.groupingBy(NetWorkVO::getCity));
        cityMap.forEach((s, netWorkVOS) -> {
            CityNetWorkVO cityNetWorkVO = new CityNetWorkVO();
            double hours = 0;
            int sum = 0;
            for (NetWorkVO netWorkVO : netWorkVOS) {
                hours += Double.valueOf(netWorkVO.getHours());
                sum += Integer.parseInt(netWorkVO.getSum());
            }
            cityNetWorkVO.setHours(String.valueOf(hours));
            cityNetWorkVO.setList(netWorkVOS);
            cityNetWorkVO.setSum(String.valueOf(sum));
            cityNetWorkVO.setCity(s);
            voList.add(cityNetWorkVO);
        });
        return voList;
    }

    public Map<String, Object> getDataByTime(String dateTime) {
        String[] split = dateTime.split(",");
        Map<String, List<ModernIndex>> modernIndexMap = modernIndexJpa.findByDateTimeIn(split).stream().collect(Collectors.groupingBy(ModernIndex::getDateTime));
        Map<String, List<ModernIndexScore>> modernIndexScoreMap = modernIndexScoreJpa.findByDateTimeIn(split).stream().collect(Collectors.groupingBy(ModernIndexScore::getDateTime));
        Map<String, Object> dataMap = new HashMap();


        for (String s : split) {
            List<ModernIndex> modernIndices = modernIndexMap.get(s);
            ModernIndex modernIndex = new ModernIndex();
            modernIndex.setDateTime(s);
            if (CollectionUtils.isNotBlank(modernIndices)) {
                modernIndex = modernIndices.get(0);
            }
            List<ModernIndexScore> modernIndexScores = modernIndexScoreMap.get(s);
            ModernIndexScore modernIndexScore = new ModernIndexScore();
            if (CollectionUtils.isNotBlank(modernIndexScores)) {
                modernIndexScore = modernIndexScores.get(0);
            }
            List list = new ArrayList();
            list.add(modernIndex);
            list.add(modernIndexScore);
            dataMap.put(s, list);
        }


        modernIndexMap.forEach((s, modernIndices) -> {
            ModernIndex modernIndex = modernIndices.get(0);
            ModernIndexScore modernIndexScore = new ModernIndexScore();
            if (CollectionUtils.isNotBlank(modernIndexScoreMap.get(s))) {
                modernIndexScore = modernIndexScoreMap.get(s).get(0);
            }
            List list = new ArrayList();
            list.add(modernIndex);
            list.add(modernIndexScore);
            dataMap.put(s, list);
        });
        Map<String, Object> map = new TreeMap<>(dataMap);
        return map;
    }

    //  现代化指标评分
    public void calculateNetWorkScore(String dateTime) {
        ModernIndex modernIndex = modernIndexJpa.findByDateTime(dateTime);
        //查询上一年的指标值
        ModernIndex oldModernIndex = modernIndexJpa.findByDateTime(String.valueOf(Integer.valueOf(dateTime) - 1));
        ModernIndexScore modernIndexScore = modernIndexScoreJpa.findByDateTime(dateTime);
        if (modernIndexScore == null) {
            modernIndexScore = new ModernIndexScore();
        }
        if (oldModernIndex == null) {
            oldModernIndex = new ModernIndex();
        }
        modernIndexScore.setDateTime(dateTime);
        //cpu核数得分
        Long cpuNum = modernIndex.getCpuNum();
        if (cpuNum != null) {
            double valueScore = 0;
            if (cpuNum < 1000) {
                valueScore = 50;
            } else if (cpuNum >= 1000 && cpuNum < 3000) {
                valueScore = 60;
            } else if (cpuNum >= 3000 && cpuNum < 5000) {
                valueScore = 70;
            } else if (cpuNum >= 5000 && cpuNum < 7000) {
                valueScore = 80;
            } else if (cpuNum >= 7000 && cpuNum < 9000) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setCpuNum(valueScore);
        }

        //cpu存储能力得分
        String cpuStorage = modernIndex.getCpuStorage();
        if (!StringUtils.isEmpty(cpuStorage)) {
            double value = Double.valueOf(cpuStorage);
            double valueScore = 0;
            if (value < 0.2) {
                valueScore = 50;
            } else if (value >= 0.2 && value < 2) {
                valueScore = 60;
            } else if (value >= 2 && value < 5) {
                valueScore = 70;
            } else if (value >= 5 && value < 9) {
                valueScore = 80;
            } else if (value >= 9 && value < 14) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setCpuStorage(valueScore);
        }

        //CPU日平均利用率得分
        String cpuDayAvg = modernIndex.getCpuDayAvg();
        if (!StringUtils.isEmpty(cpuDayAvg)) {
            double value = Double.valueOf(cpuDayAvg);
            double valueScore = 0;
            if (value < 5) {
                valueScore = 50;
            } else if (value >= 5 && value < 10) {
                valueScore = 60;
            } else if (value >= 10 && value < 30) {
                valueScore = 70;
            } else if (value >= 30 && value < 50) {
                valueScore = 100;
            } else if (value >= 50 && value < 70) {
                valueScore = 90;
            } else {
                valueScore = 80;
            }
            modernIndexScore.setCpuDayAvg(valueScore);
        }

        //CPU日峰值利用率得分
        String cpuDayMax = modernIndex.getCpuDayMax();
        if (!StringUtils.isEmpty(cpuDayMax)) {
            double value = Double.valueOf(cpuDayMax);
            double valueScore = 0;
            if (value < 10) {
                valueScore = 30;
            } else if (value >= 10 && value < 20) {
                valueScore = 50;
            } else if (value >= 20 && value < 50) {
                valueScore = 70;
            } else if (value >= 50 && value < 70) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setCpuDayMax(valueScore);
        }


        //存储利用率
        String cpuStorageRate = modernIndex.getCpuStorageRate();
        if (!StringUtils.isEmpty(cpuStorageRate)) {
            double value = Double.valueOf(cpuStorageRate);
            double valueScore = 0;
            if (value < 30) {
                valueScore = 50;
            } else if (value >= 30 && value < 50) {
                valueScore = 70;
            } else if (value >= 50 && value < 70) {
                valueScore = 90;
            } else if (value >= 70 && value < 80) {
                valueScore = 100;
            } else if (value >= 80 && value < 90) {
                valueScore = 85;
            } else {
                valueScore = 60;
            }
            modernIndexScore.setCpuStorageRate(valueScore);
        }

        //省地广域网链接带宽
        String provinceLink = modernIndex.getProvinceLink();
        if (!StringUtils.isEmpty(provinceLink)) {
            double value = Double.valueOf(provinceLink);
            double valueScore = 0;
            if (value < 20) {
                valueScore = 60;
            } else if (value >= 20 && value < 100) {
                valueScore = 70;
            } else if (value >= 100 && value < 200) {
                valueScore = 80;
            } else if (value >= 200 && value < 300) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setProvinceLink(valueScore);
        }

        //地县广域网链接带宽
        String countyLink = modernIndex.getCountyLink();
        if (!StringUtils.isEmpty(countyLink)) {
            double value = Double.valueOf(countyLink);
            double valueScore = 0;
            if (value < 25) {
                valueScore = 60;
            } else if (value >= 25 && value < 50) {
                valueScore = 70;
            } else if (value >= 50 && value < 100) {
                valueScore = 80;
            } else if (value >= 100 && value < 150) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setCountyLink(valueScore);
        }

        //国省宽带网带宽利用率
        String countyRate = modernIndex.getCountyRate();
        if (!StringUtils.isEmpty(countyRate)) {
            double value = Double.valueOf(countyRate);
            double valueScore = 0;
            if (value < 20) {
                valueScore = 60;
            } else if (value >= 20 && value < 30) {
                valueScore = 75;
            } else if (value >= 30 && value < 50) {
                valueScore = 85;
            } else if (value >= 50 && value < 75) {
                valueScore = 100;
            } else if (value >= 75 && value < 90) {
                valueScore = 90;
            } else {
                valueScore = 85;
            }
            modernIndexScore.setCountyRate(valueScore);
        }

        //互联网出口带宽
        String networkExit = modernIndex.getNetworkExit();
        if (!StringUtils.isEmpty(networkExit)) {
            double value = Double.valueOf(networkExit);
            double valueScore = 0;
            if (value < 400) {
                valueScore = 60;
            } else if (value >= 400 && value < 700) {
                valueScore = 70;
            } else if (value >= 700 && value < 1000) {
                valueScore = 80;
            } else if (value >= 1000 && value < 1400) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setNetworkExit(valueScore);
        }

        //三级系统等保测评通过率
        String threeLevelSystemRate = modernIndex.getThreeLevelSystemRate();
        if (!StringUtils.isEmpty(threeLevelSystemRate)) {
            modernIndexScore.setThreeLevelSystemRate(Double.valueOf(threeLevelSystemRate));
        }

        //三级等保系统测评评分（平均）
        String threeLevelSystemAvg = modernIndex.getThreeLevelSystemAvg();
        if (!StringUtils.isEmpty(threeLevelSystemAvg)) {
            modernIndexScore.setThreeLevelSystemAvg(Double.valueOf(threeLevelSystemAvg));
        }

        //是否出现网络安全事故
        String networkSecurityIncidents = modernIndex.getNetworkSecurityIncidents();
        if (!StringUtils.isEmpty(networkSecurityIncidents)) {
            modernIndexScore.setNetworkSecurityIncidents(networkSecurityIncidents.equals("是") ? 0d : 100d);
        }

        //收集资料种数
        Long dataCollectNum = modernIndex.getDataCollectNum();
        Long lastYearNum = oldModernIndex.getDataCollectNum();
        if (dataCollectNum != null && lastYearNum != null) {
            double valueScore = 0;
            if (dataCollectNum < 100) {
                valueScore = 5;
            } else if (dataCollectNum >= 100 && dataCollectNum < 200) {
                valueScore = 10;
            } else if (dataCollectNum >= 200 && dataCollectNum < 300) {
                valueScore = 15;
            } else if (dataCollectNum >= 300 && dataCollectNum < 400) {
                valueScore = 20;
            } else if (dataCollectNum >= 400 && dataCollectNum < 500) {
                valueScore = 25;
            } else {
                valueScore = 30;
            }

            int increment = 0;
            if (dataCollectNum > lastYearNum) {
                increment = (int) (dataCollectNum - lastYearNum);
            }
            modernIndexScore.setDataCollectNum(valueScore + increment);
        }

        //数据收集时效（区域自动站考核是否达标）
        String regionDataCollectTime = modernIndex.getRegionDataCollectTime();
        if (!StringUtils.isEmpty(regionDataCollectTime)) {
            modernIndexScore.setRegionDataCollectTime(regionDataCollectTime.equals("是") ? 50d : 0d);
        }

        //数据收集时效（雷达考核是否达标）
        String radarDataCollectTime = modernIndex.getRadarDataCollectTime();
        if (!StringUtils.isEmpty(radarDataCollectTime)) {
            modernIndexScore.setRadarDataCollectTime(radarDataCollectTime.equals("是") ? 50d : 0d);
        }

        //收集数据的共享率（共享种数）
        String dataCollectRate = modernIndex.getDataCollectRate();
        String collectRate = modernIndex.getCollectRate();
        if (!StringUtils.isEmpty(dataCollectRate) && !StringUtils.isEmpty(collectRate)) {
            double v = Double.valueOf(dataCollectRate) / Double.valueOf(collectRate) * 100;
            v = (double) Math.round(v * 100) / 100;
            modernIndexScore.setDataCollectRate(v);
            modernIndexScore.setCollectRate(v);
        }

        //已纳入质控的数据种类
        String controlDataNum = modernIndex.getControlDataNum();
        if (!StringUtils.isEmpty(controlDataNum)) {
            Double value = Double.valueOf(controlDataNum);
            double v = value / 6 * 100;
            v = (double) Math.round(v * 100) / 100;
            modernIndexScore.setControlDataNum(v);

        }


        //综合数据质量评分
        String qualityDataScore = modernIndex.getQualityDataScore();
        if (!StringUtils.isEmpty(qualityDataScore)) {
            modernIndexScore.setQualityDataScore(Double.valueOf(qualityDataScore));
        }

        //本省新增算法
        String countyNewAlgorithm = modernIndex.getProvinceNewAlgorithm();
        if (!StringUtils.isEmpty(countyNewAlgorithm)) {
            double value = Double.valueOf(countyNewAlgorithm);
            double valueScore = 0;
            if (value < 10) {
                valueScore = 70;
            } else if (value >= 10 && value < 20) {
                valueScore = 75;
            } else if (value >= 20 && value < 40) {
                valueScore = 85;
            } else if (value >= 40 && value < 60) {
                valueScore = 95;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setProvinceNewAlgorithm(valueScore);
        }

        //算法改进数量
        String updateAlgorithm = modernIndex.getUpdateAlgorithm();
        if (!StringUtils.isEmpty(updateAlgorithm)) {
            double value = Double.valueOf(updateAlgorithm);
            double valueScore = 0;
            if (value < 5) {
                valueScore = 20;
            } else if (value >= 5 && value < 10) {
                valueScore = 40;
            } else if (value >= 10 && value < 20) {
                valueScore = 60;
            } else if (value >= 20 && value < 40) {
                valueScore = 80;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setUpdateAlgorithm(valueScore);
        }

        //算法共享数量
        String shareAlgorithm = modernIndex.getShareAlgorithm();
        if (!StringUtils.isEmpty(shareAlgorithm)) {
            double value = Double.valueOf(shareAlgorithm);
            double valueScore = 0;
            if (value < 5) {
                valueScore = 60;
            } else if (value >= 5 && value < 10) {
                valueScore = 70;
            } else if (value >= 10 && value < 20) {
                valueScore = 80;
            } else if (value >= 20 && value < 40) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setShareAlgorithm(valueScore);
        }

        //产品输出种类
        String productOutputTypes = modernIndex.getProductOutputTypes();
        if (!StringUtils.isEmpty(productOutputTypes)) {
            double value = Double.valueOf(productOutputTypes);
            double valueScore = 0;
            if (value < 100) {
                valueScore = 60;
            } else if (value >= 100 && value < 200) {
                valueScore = 70;
            } else if (value >= 200 && value < 300) {
                valueScore = 80;
            } else if (value >= 300 && value < 500) {
                valueScore = 90;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setProductOutputTypes(valueScore);
        }

        //数据接口响应时效
        String interfaceResponseTime = modernIndex.getInterfaceResponseTime();
        if (!StringUtils.isEmpty(interfaceResponseTime)) {
            double valueScore = 0;
            if (interfaceResponseTime.equals("小于1秒")) {
                valueScore = 25;
            } else if (interfaceResponseTime.equals("1-10秒")) {
                valueScore = 10;
            } else {
                valueScore = 0;
            }
            modernIndexScore.setInterfaceResponseTime(valueScore);
        }

        //接口访问量
        String dataAccess = modernIndex.getDataAccess();
        if (!StringUtils.isEmpty(dataAccess)) {
            double value = Double.valueOf(dataAccess);
            double valueScore = 0;
            if (value < 10) {
                valueScore = 5;
            } else if (value >= 10 && value < 100) {
                valueScore = 10;
            } else if (value >= 100 && value < 500) {
                valueScore = 15;
            } else if (value >= 500 && value < 1000) {
                valueScore = 20;
            } else {
                valueScore = 25;
            }
            modernIndexScore.setDataAccess(valueScore);
        }

        //数据服务量
        String dataService = modernIndex.getDataService();
        if (!StringUtils.isEmpty(dataService)) {
            double value = Double.valueOf(dataService);
            double valueScore = 0;
            if (value < 100) {
                valueScore = 0;
            } else if (value >= 100 && value < 500) {
                valueScore = 2;
            } else if (value >= 500 && value < 1024) {
                valueScore = 5;
            } else if (value >= 1024 && value < 10240) {
                valueScore = 10;
            } else if (value >= 10240 && value < 102400) {
                valueScore = 15;
            } else if (value >= 102400 && value < 512000) {
                valueScore = 20;
            } else {
                valueScore = 25;
            }
            modernIndexScore.setDataService(valueScore);
        }

        //行业覆盖率
        String industryCoverage = modernIndex.getIndustryCoverage();
        if (!StringUtils.isEmpty(industryCoverage)) {
            double value = Double.valueOf(industryCoverage);
            double valueScore = 0;
            if (value < 50) {
                valueScore = 0;
            } else if (value >= 50 && value < 70) {
                valueScore = 10;
            } else if (value >= 70 && value < 80) {
                valueScore = 15;
            } else if (value >= 80 && value < 90) {
                valueScore = 20;
            } else {
                valueScore = 25;
            }
            modernIndexScore.setIndustryCoverage(valueScore);
        }

        //是否实现网络统一出口管理
        String networkManagment = modernIndex.getNetworkManagment();
        if (!StringUtils.isEmpty(networkManagment)) {
            modernIndexScore.setNetworkManagment(networkManagment.equals("是") ? 100d : 0d);
        }

        //核心观测数据纳入安全监管种类
        Long coreDataNum = modernIndex.getCoreDataNum();
        if (coreDataNum != null) {
            double valueScore = 0;
            if (coreDataNum == 0) {
                valueScore = 0;
            } else if (coreDataNum >= 1 && coreDataNum < 3) {
                valueScore = 60;
            } else if (coreDataNum >= 3 && coreDataNum < 5) {
                valueScore = 70;
            } else if (coreDataNum >= 5 && coreDataNum < 7) {
                valueScore = 80;
            } else if (coreDataNum == 7) {
                valueScore = 9;
            } else {
                valueScore = 100;
            }
            modernIndexScore.setCoreDataNum(valueScore);
        }

        //todo 后期可能会改动
        //融入天擎的业务系统个数（无自建数据库）
        Long tianqingSystemNum = modernIndex.getTianqingSystemNum();
        if (tianqingSystemNum != null) {
            double v = Double.valueOf(tianqingSystemNum) / 73 * 100;
            v = (double) Math.round(v * 100) / 100;
            modernIndexScore.setTianqingSystemNum(v);
        }

        //天镜系统个数
        Long tianjingSystemNum = modernIndex.getTianjingSystemNum();
        if (tianjingSystemNum != null) {
            double v = Double.valueOf(tianjingSystemNum) / 73 * 100;
            v = (double) Math.round(v * 100) / 100;
            modernIndexScore.setTianjingSystemNum(v);
        }
        modernIndexScoreJpa.save(modernIndexScore);
    }

    public List<IndexConfig> getIndexConfigByDateTime(String dateTime) {
        List<IndexConfig> indexConfigs = indexConfigJpa.findByDateTime(dateTime);
        return indexConfigs;
    }

    @Transactional
    public String updateIndexConfig(List<IndexConfig> list) {
        List<IndexConfig> deleteList = list.stream().filter(indexConfig -> indexConfig.getType() == 999).collect(Collectors.toList());
        List<IndexConfig> updateList = list.stream().filter(indexConfig -> indexConfig.getType() != 999).collect(Collectors.toList());
        try {
            indexConfigJpa.saveAll(updateList);
            indexConfigJpa.deleteAll(deleteList);
            return "保存成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "保存失败";
        }
    }


    public InputStream getResourceTemplatePath(String path) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(path);
        return classPathResource.getInputStream();
    }

    public Map<String, Object> getNetworkFailureInfo(String startMonth, String endMonth) {
        Map<String, Object> map = new HashMap<>();
        List<FailureRecord> failureRecords = failureRecordJpa.findByDateTimeBetween(startMonth, endMonth);
        if (failureRecords.isEmpty()) {
            map.put("code", -1);
            map.put("message", "当前时间范围内无数据");
            return map;
        }
        List<NetworkResolveVo> resolveVoList = failureRecords.stream().map(failureRecord -> {
            NetworkResolveVo networkResolveVo = new NetworkResolveVo();
            BeanUtils.copyProperties(failureRecord, networkResolveVo);
            long startTime = DateUtil.str2DateByFormat(failureRecord.getStartTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime();
            long getSolveTime = DateUtil.str2DateByFormat(failureRecord.getSolveTime(), DateUtil.WEB_FORMATOR_YMDH3).getTime();
            Double resolveTime = (getSolveTime - startTime) * 1.0 / CommonValue.hour;
            networkResolveVo.setResolveHours(resolveTime);
            networkResolveVo.setHappenedDate(LocalDateTimeUtil.of(startTime));
            return networkResolveVo;
        }).collect(Collectors.toList());

        // 总时长
        double totalHours = resolveVoList.stream().mapToDouble(NetworkResolveVo::getResolveHours).sum();
        // 总次数
        int totalSum = failureRecords.size();


        // 最长故障时长对象
        NetworkResolveVo resolveVo = resolveVoList.stream().max(Comparator.comparingDouble(NetworkResolveVo::getResolveHours)).get();

        map.put("longestHour", NumberUtil.round(resolveVo.getResolveHours(), 1));
        map.put("place", resolveVo.getPlace());
        map.put("totalHour", NumberUtil.round(totalHours, 1));
        map.put("totalSum", totalSum);
        map.put("date", LocalDateTimeUtil.format(resolveVo.getHappenedDate(), "yyyy/MM/dd"));
        map.put("code", 1);
        return map;
    }


}
